package com.gzy.literature.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

@WebFilter(filterName = "EncodingFilter", urlPatterns = "/*",
        initParams = @WebInitParam(name = "encoding", value = "UTF-8"))
public class EncodingFilter implements Filter {
    private String encoding;

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.encoding = config.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // 设置请求和响应的字符编码
        req.setCharacterEncoding(encoding);
        res.setCharacterEncoding(encoding);

        // 包装请求以修改参数编码
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(req) {
            @Override
            public Map<String, String[]> getParameterMap() {
                Map<String, String[]> map = super.getParameterMap();
                for (String key : map.keySet()) {
                    String[] values = map.get(key);
                    for (int i = 0; i < values.length; i++) {
                        try {

                            values[i] = new String(values[i].getBytes("ISO-8859-1"), encoding);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();

                        }
                    }
                }
                return map;
            }
            @Override
            public String getParameter(String name) {
                String[] values = getParameterValues(name);
                if (values == null || values.length == 0) {
                    return null;
                }
                return values[0];
            }

            @Override
            public String[] getParameterValues(String name) {
                Map<String, String[]> map = getParameterMap();
                return map.get(name);
            }
        };
        chain.doFilter(requestWrapper, res);
    }

    @Override
    public void destroy() {
        // 清理资源（如果需要）
    }
}